package com.jx.controller;

import com.jx.entity.User;
import com.jx.service.UserService;
import com.jx.utils.StringUtil;
import com.wf.captcha.utils.CaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: xiao
 * @dateTime: 2021/11/15 17:20
 */
@Controller
@RequestMapping(value = "/register")
public class RegisterController {

    @Resource
    private UserService userService;

    /**
     * 注册页面
     * @param model
     * @return
     */
    @RequestMapping(value = "/registerForm")
    public String registerForm(Model model){
        return "login/registerForm";
    }


    /**
     * 注册
     * @return
     */
    @RequestMapping(value = "/register")
    @ResponseBody
    public Map<String,Object> register(HttpSession session,HttpServletRequest request,
                                       User user){
        Map<String,Object>map = new HashMap();
        if(user == null){
            map.put("code","1000");
            map.put("msg","请输入正确的用户信息");
        } else {
            User u = new User();
            u.setName(user.getName());
            List<User> nuser = userService.getUserByUser(u);
            if(nuser != null && nuser.size() > 0){
                map.put("code","name");
                map.put("msg","昵称重复，请重新输入！");
                return map;
            }

            u.setName(null);
            u.setUsername(user.getUsername());
            List<User> uuser = userService.getUserByUser(u);
            if(uuser != null && uuser.size() > 0){
                map.put("code","username");
                map.put("msg","用户名重复，请重新输入！");
                return map;
            }

            int i = userService.register(user);
            map.put("code",i);
        }

        return map;
    }

    /**
     * 验证码
     * @param request
     * @param response
     */
    @RequestMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) {
        try {
            CaptchaUtil.out(request, response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
